/**
 * Ruler module
 */
import React from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'dva';
import pagesActions from '../../../../actions/Editor/pages';
import editorSize from '../../../../consts/editorSize';
import editorActions from '../../../../actions/Editor/editor';

class Ruler extends React.Component {
    componentWillMount() {
        this.isMoving = false;
        this.startPosition = {
            x: 0,
            y: 0,
        };
        this.movingPosition = {
            x: 0,
            y: 0,
        };
        this.Drag = null;
        this.dragFlag = false;
        this.drag_v = false;
    }
    componentDidMount() {
        const headerId = 'ScaleRulerH';
        this.initElements();
        if (this.elements.ScaleRuler_h.length) {
            this.createRuler();
            this.bindEvent();
        }
    }
    componentDidUpdate() {
        this.initElements();
        if (this.elements.ScaleRuler_h.length) {
            this.elements.ScaleRuler_h.html('');
            this.elements.ScaleRuler_v.html('');
            this.createRuler();
            this.bindEvent();
        }
    }
    initElements() {
        this.elements = {
            ruler: $('.Ruler'),
            editorPanel: $('.creator-editor'),
            ScaleRuler_h: $(this.refs.ScaleRulerH),
            ScaleRuler_v: $(this.refs.ScaleRulerV),
            RefLine: $('.RefLine'),
            RefLine_v: $('.RefLine_v'),
            doth: $(this.refs.RefDotH),
            dotv: $(this.refs.RefDotV),
            canvas: $('.editor-canvas'),
        };
        this.elements.RefLine.draggable();
    }
    updateRulerPosition(left, top){
        var leftP = {left: left};
        var topP = {top: top};
        this.elements.ScaleRuler_h.css(topP);
        this.elements.ScaleRuler_v.css(leftP);
    }
    createRuler() {
         $.pageRuler();
        this.createTimeline();
    }
    createTimeline() {
        const canvasH = "<canvas id='ruler_h' width='4000' height='18'></canvas>";
        const canvasV = "<canvas id='ruler_v' width='18' height='4000'></canvas>";
        $(canvasH).appendTo(this.elements.ScaleRuler_h);
        $(canvasV).appendTo(this.elements.ScaleRuler_v);

        const scrollTop = editorSize.view.height / 2 - 700;
        const scrollLeft = editorSize.view.width / 2 - 700;
        const area = {
            width: parseFloat(editorSize.editor_width),
            height: parseFloat(editorSize.editor_height),
        };
        const opt = {
            scrollTop,
            scrollLeft,
            area,
        };

        const rh = this.elements.ScaleRuler_h,
            rv = this.elements.ScaleRuler_v;
        const mycanvasH = document.getElementById('ruler_h').getContext('2d');
        const mycanvasV = document.getElementById('ruler_v').getContext('2d');
        let boxWidth = $('.editorquyu').width(),
            boxHeight = $('.editorquyu').height();

        const startH = -parseInt(opt.scrollTop + boxWidth / 2);
        const startV = -parseInt(opt.scrollLeft + boxHeight / 2);
        mycanvasH.font = '.5px Calibri';
        mycanvasV.font = '.5px Calibri';
        for (var i = 0; i < 4000; i++) {
            mycanvasH.moveTo(0, 18);
            mycanvasH.strokeStyle = '#959fb0';
            mycanvasH.lineWidth = '.5';
            if ((i + startH) % 10 === 0) {
                mycanvasH.beginPath();
                mycanvasH.moveTo(i, 18);
                if ((i + startH) % 100 === 0) {
                    mycanvasH.lineTo(i, 0);
                    $(`<span class="n">${i + startH}</span>`).css('left', i + 5).appendTo(rh);
                } else {
                    mycanvasH.lineTo(i, 12);
                }
                mycanvasH.stroke();
            }
        }
        for (var i = 0; i < 4000; i++) {
            mycanvasV.moveTo(18, 0);
            mycanvasV.strokeStyle = '#959fb0';
            mycanvasV.lineWidth = '.25';
            if ((i + startV) % 10 == 0) {
                mycanvasV.beginPath();
                mycanvasV.moveTo(18, i);
                if ((i + startV) % 100 == 0) {
                    mycanvasV.lineTo(0, i);
                    $(`<span class="n">${i + startV}</span>`).css('top', i - 12).appendTo(rv);
                } else {
                    mycanvasV.lineTo(13, i);
                }
                mycanvasV.stroke();
            }
        }
    }
    UpdateSelectedLine() {
        const self = this;
        function mouseDown(e) {
            self.selectLine = $(e.target || e.srcElement);
            self.oDrag = self.selectLine;
            self.dragFlag = true;

            if (self.selectLine.hasClass('RefLine_v')) {
                self.drag_v = true;
            } else {
                self.drag_v = false;
            }
        }
        $(this.refs.lines).mousedown(mouseDown);
        this.elements.RefLine.mousedown(mouseDown);
        $(this.refs.lines).draggable();
    }
    bindEvent() {
        const self = this;

        function rvMouseDown(e) {
            if (!self.oDrag) self.oDrag = self.newv();
            self.dragFlag = true;
            self.drag_v = true;
        }
        function rhMouseDown(e) {
            if (!self.oDrag) self.oDrag = self.newh();
            self.dragFlag = true;
            self.drag_v = false;
        }

        function MouseUp(e) {
            this.dragFlag = false;
            const scrollTop = self.elements.editorPanel.scrollTop();
            const scrollLeft = self.elements.editorPanel.scrollLeft();
            let param = null;
            const data = {};
            if (self.oDrag) {
                const id = self.oDrag.selector || self.oDrag.attr('id');
                if (self.drag_v) {
                    let vL = e.pageX + scrollLeft - 66;
                    if (vL < self.elements.ScaleRuler_v.width()) {
                        vL = -600;
                    }
                    param = {
                        position: {
                            left: `${vL}px`,
                            top: 0,
                        },
                        className: 'RefLine_v RefLine',
                        id,
                    };
                } else {
                    let vT = e.pageY + scrollTop - 83;
                    if (vT < self.elements.ScaleRuler_h.height()) {
                        vT = 600;
                    }
                    param = {
                        position: {
                            left: 0,
                            top: `${vT}px`,
                        },
                        className: 'RefLine_h RefLine',
                        id,
                    };
                }
                data[id] = param;

                const {updatePage,page} = self.props;
                const {reference_line} = page || {};
                let _data = $.extend(reference_line, data);
                updatePage({reference_line: _data,page_id:page.page_id});
                self.initElements();
                self.elements.dotv.css("left",0);
                self.elements.doth.css("top",0);
            }
            self.oDrag = null;
            self.drag_v = false;
        }
        this.elements.ScaleRuler_v.mousedown(rvMouseDown);
        this.elements.ScaleRuler_h.mousedown(rhMouseDown);
        this.elements.editorPanel.mouseup(MouseUp);
    }
    newv(t) { // 创建新的垂直参考线，有效宽度3像素
        const id = `RefLineV${$('.RefLine_v').size() + 1}`;
        return $(`#${id}`);
    }
    newh(t) { // 创建新的垂直参考线，有效宽度3像素
        const id = `RefLineH${$('.RefLine_h').size() + 1}`;
        return $(`#${id}`);
    }
    updateStateLines(id, type) {
        const { page, setState , updatePage} = this.props;
        let toggleAllLineVisible = this.props.toggleAllLineVisible;
        let param = null;
        if (type === 'delete') {
            delete page.reference_line[id];
        } else {
            param = {
                display: 'none',
            };
            $.extend(page.reference_line[id].position, param);

            toggleAllLineVisible = !toggleAllLineVisible;
            root.updateMenus('editor');
        }
//        root.setState({
//            page,
//            toggleAllLineVisible,
//        });
        updatePage(page);
    }
    render() {
        const {page,rulerLeft,rulerTop} = this.props;
        let top ={
            top: rulerTop+'px'
        }
        let left = {
            left:rulerLeft+'px'
        }
        let newLines = page ? page.reference_line || [] : [];
        delete newLines.visible;
        let arr = [];
        for(let item in newLines){
            arr.push(newLines[item]);
        }
        return (
          <div className="ScaleBox" id="ScaleBox">
            <div id="ScaleRulerH" className="ScaleRuler_h" ref="ScaleRulerH" style={top} />
            <div id="ScaleRulerV" className="ScaleRuler_v" ref="ScaleRulerV" style={left} />
            <div id="RefDotH" className="RefDot_h" ref="RefDotH" />
            <div id="RefDotV" className="RefDot_v" ref="RefDotV" />
            <div className="RefCrtBg" id="RefCrtBg" style={{ display: 'none' }}>
              <div className="RefCrtTit">
                <a href="javascript:void(0);" id="RefCrtClose" className="RefCrtClose" />
              </div>
            </div>
            {
                arr.map((line) => {
                    return (
                      <div className={line.className} style={line.position} key={line.id} id={line.id} ref="lines" />
                    );
                })
            }
          </div>
        );
    }
}

const mapStateToProps = ({ editor, pages}) => {
  const pageId = editor.selectedPageId;
  return {
      page: pages.filter(p => p.page_id === pageId)[0],
      rulerLeft: editor.rulerLeft,
      rulerTop: editor.rulerTop,
  };
};

const mapDispatchToProps = (dispatch) => {
  return bindActionCreators(pagesActions, dispatch);
};


export default connect(mapStateToProps, mapDispatchToProps)(Ruler);
module.exports = Ruler;
